package com.powergisol.gis.controller;

import com.google.code.kaptcha.Producer;
import com.powergisol.gis.model.RASUtils;
import com.powergisol.gis.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping(value = "code")
public class LoginController {
    @Autowired
    private Producer producer;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/getCaptcha")
    public void getCode(HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
//        HttpSession session = request.getSession();
//        session.setAttribute("imageCode",text);
        //保存验证码信息
        String randomStr = request.getParameter("randomStr");
        redisTemplate.opsForValue().set("imageCode" + randomStr, text, 120, TimeUnit.SECONDS);
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }
    /**
     * 验证验证码
     *
     * @param code
     */
    @GetMapping("checkCaptcha")
    public Result checkCaptcha(String code, HttpServletRequest request) {
        try {
            String randomStr = request.getParameter("randomStr");
            String key = "imageCode" + randomStr;
            if (!redisTemplate.hasKey(key)) {
                return new Result().failure(-1,"请重新获取验证码");
            }
            Object codeObj = redisTemplate.opsForValue().get(key);

            if (codeObj == null) {
                return new Result().failure(-1,"请重新获取验证码");
            }

            String saveCode = codeObj.toString();
            if (null == saveCode) {
                redisTemplate.delete(key);
                return new Result().failure(-1,"验证码不能为空");
            }
            if (!saveCode.equalsIgnoreCase(code)) {
                redisTemplate.delete(key);
                return new Result().failure(-1,"验证码错误");
            }
            redisTemplate.delete(key);
        } catch (Exception e) {
            return new Result().failure(-1, e.getMessage());
        }
        return new Result().success();
    }
    @GetMapping("getkey")
    public Result getKey(String randomStr) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        RSAPublicKey rsapPublicKey = null;
        RSAPrivateKey rsaPrivateKey = null;
        try {
            KeyPair publicKey = RASUtils.generateKeyPair();
            rsapPublicKey = (RSAPublicKey) publicKey.getPublic();
            rsaPrivateKey = (RSAPrivateKey) publicKey.getPrivate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisTemplate.opsForValue().set("privateKey" + randomStr, rsaPrivateKey, 120, TimeUnit.SECONDS);
        hashMap.put("publicKey", rsapPublicKey.getModulus().toString(16));
        return new Result().success(hashMap);
    }
}
